import pytest
from fastapi.testclient import TestClient
from sqlmodel import Session, SQLModel, create_engine
from sqlmodel.pool import StaticPool

from app.main import app

from app.core.db import get_session

from app.models.user import User
from app.core.security import get_password_hash

@pytest.fixture(name="session")
def session_fixture():
    engine = create_engine(
        "sqlite://",
        connect_args={"check_same_thread": False},
        poolclass=StaticPool
    )
    SQLModel.metadata.create_all(engine)
    with Session(engine) as session:
        yield session


@pytest.fixture(name="client")
def client_fixture(session: Session):
    def get_session_overrides():
        return session

    app.dependency_overrides[get_session] = get_session_overrides
    client = TestClient(app)
    yield client
    app.dependency_overrides.clear()


def test_login(session:Session, client: TestClient):
    user = User(email="123@123.com", hashed_password=get_password_hash("123"))
    session.add(user)
    session.commit()
    response = client.post("/auth/login", data={"username": "123@123.com", "password": "123"})
    data = response.json()
    print(data)
    assert response.status_code == 200
    assert data["access_token"] is not None
